package com.project.persistence.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import com.project.configuration.ConfigurationProvider;

public class Connect {
	
	private static Connection conn;

    private Connection openConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
        Properties properties = ConfigurationProvider.getInstance().getConfiguration();

            Class.forName(properties.getProperty("db.driver")).newInstance();
            conn = DriverManager.getConnection(properties.getProperty("db.url"), properties.getProperty("db.username"),
            		properties.getProperty("db.password"));
        return conn;
    }

    public void closeConnection() {
       
        try {
            if (Connect.conn != null && !Connect.conn.isClosed()) {
            	Connect.conn.close();
            	Connect.conn = null;
            }
        } catch (SQLException e) {
        	e.printStackTrace();
        }
        
    }

    /**
     * @return the conn
     * @throws SQLException 
     * @throws ClassNotFoundException 
     * @throws IllegalAccessException 
     * @throws InstantiationException 
     */
    public Connection getConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
        if (Connect.conn != null) {
            return Connect.conn;
        } else {
            return openConnection();
        }
    }

    /**
     * @param conn the conn to set
     */
    public void setConnection(Connection connection) {
    	Connect.conn = connection;
    }

}
